package com.starblink.login.accountmanagement.ui

import android.content.Intent
import com.alibaba.android.arouter.facade.annotation.Route
import android.os.Bundle
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginResult
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.ApolloModelExt.getThirdLoginInfo
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.android.basic.user.login.FacebookLoginUtils
import com.starblink.android.basic.user.login.GoogleLoginUtils
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.feedback.LogoutDialog
import com.starblink.login.databinding.ActivityAccountManagementBinding
import com.starblink.login.signin.ui.SigninActivity
import com.starblink.rocketreserver.type.LoginChannel

/**
 * 账户管理页面
 */
@Route(path = RoutePage.Login.ACCOUNT_MANAGEMENT)
class AccountManagementActivity :
    BaseTVMActivity<ActivityAccountManagementBinding, AccountManagementVM>() {
    companion object {
        const val REQUEST_CODE_GOOGLE_LOGIN = 102 // 谷歌登录
    }

    override fun initViewBinding(): ActivityAccountManagementBinding =
        ActivityAccountManagementBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //返回按钮
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })


        viewBinding.aamEmail.fdBtnText.text =
            CommUtils.getString(com.starblink.basic.style.R.string.email)
        viewBinding.aamEmail.fdBtnText.setTextColor(CommUtils.getColor(R.color.gu_text_secondary))

        viewBinding.aamFacebook.fdBtnText.text =
            CommUtils.getString(com.starblink.basic.style.R.string.facebook)
        viewBinding.aamGoogle.fdBtnText.text =
            CommUtils.getString(com.starblink.basic.style.R.string.google)
        viewBinding.aamDeleteAccount.fdBtnText.text = CommUtils.getString(R.string.delete_account2)

        viewBinding.aamEmail.fdBtnText2.hint = ""
        viewBinding.aamDeleteAccount.fdBtnText2.hint = ""

        viewBinding.aamEmail.fdBtnText2.text = UserDataCenter.getAccountInfo()?.email



        //跑马灯
        viewBinding.aamEmail.fdBtnText2.isSelected = true
        viewBinding.aamFacebook.fdBtnText2.isSelected = true
        viewBinding.aamGoogle.fdBtnText2.isSelected = true

//      三方类型，10-facebook一键登录, 11-Google一键登录, 12-Apple一键登录
        UserDataCenter.getAccountInfo()?.thirdList?.forEach {
            when (it.loginType) {
                10 -> {
                    viewBinding.aamFacebook.fdBtnText2.text = it.userName
                    viewModel.bindFacebook = true
                    viewBinding.aamFacebook.fdBtnImg.setImageResource(com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_checked)
                }
                11 -> {
                    viewBinding.aamGoogle.fdBtnText2.text = it.userName
                    viewModel.bindGoogle = true
                    viewBinding.aamGoogle.fdBtnImg.setImageResource(com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_checked)
                }
            }
        }

        viewBinding.aamEmail.fdBtn.click {
            ConfirmDialog.Builder(this)
                .setMessage("Change the connected email address?")
                .setCancelButton(R.string.cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .setSureButton(R.string.confirm) { dialog, _ ->
                    dialog.dismiss()
                    navigationTo(RoutePage.Login.CHANGE_BOUND_EMAIL_INPUT_EMAIL)
                }
                .setCanCancel(false)
                .create().show()
        }

        viewBinding.aamFacebook.fdBtn.click {
            if (viewModel.bindFacebook) {
                // 已绑定脸书账号，进行解绑
                showUnbindThirdLoginConfirmDialog(LoginChannel.facebook, "Facebook account")
            } else {
                // 未绑定脸书，进行绑定
                if (FacebookLoginUtils.isLogin()) {
                    YYLogUtils.i("用户已登录,先登出在登录")
                    FacebookLoginUtils.signOut()
                    facebookSignIn()
                } else {
                    YYLogUtils.i("用户未登录，直接登录")
                    facebookSignIn()
                }
            }
        }

        viewBinding.aamGoogle.fdBtn.click {
            if (viewModel.bindGoogle) {
                // 已绑定谷歌账号，进行解绑
                showUnbindThirdLoginConfirmDialog(LoginChannel.google, "Google account")
            } else {
                // 未绑定谷歌，进行绑定
                if (GoogleLoginUtils.isLogin()) {
                    YYLogUtils.i("用户已登录,先登出在登录")
                    GoogleLoginUtils.signOut().addOnCompleteListener {
                        GoogleLoginUtils.signIn(this, SigninActivity.REQUEST_CODE_GOOGLE_LOGIN)
                    }
                } else {
                    YYLogUtils.i("用户未登录，直接登录")
                    GoogleLoginUtils.signIn(this, REQUEST_CODE_GOOGLE_LOGIN)
                }
            }
        }

        viewBinding.accmLogOut.click {
            LogoutDialog(this) {
                // 登出，返回首页
                LoginManager.logout()
                ActivityStackManage.toMainActivity()
            }.show(this.supportFragmentManager, "more")
        }
        viewBinding.aamDeleteAccount.fdBtn.click {
            navigation(path = RoutePage.Login.DELETE_YOUR_ACCOUNT)
        }
    }

    private fun showUnbindThirdLoginConfirmDialog(loginChannel: LoginChannel, channelName: String) {
        ConfirmDialog.Builder(this)
            .setMessage("You will not be able to log in using this $channelName after disconnecting.")
            .setCancelButton(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }
            .setSureButton(R.string.continue_) { dialog, _ ->
                dialog.dismiss()
                viewModel.unbindThirdLogin(loginChannel)
            }
            .setCanCancel(false)
            .create().show()
    }

    private fun facebookSignIn() {
        FacebookLoginUtils.signIn(
            this,
            object : FacebookCallback<LoginResult> {
                override fun onCancel() {
                    toast(R.string.connect_cancel)
                }

                override fun onError(error: FacebookException) {
                    toast(R.string.connect_fail2)
                }

                override fun onSuccess(result: LoginResult) {
                    viewModel.bindThirdLogin(LoginChannel.facebook, result.accessToken.token)
                }
            }
        )
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.unbindThirdLoginResLiveData.observe(this) {
            // 监听解绑结果
            if (it.first == LoginChannel.google) {
                if (it.second) {
                    // 解绑成功
                    viewBinding.aamGoogle.fdBtnText2.text =""
                    viewBinding.aamGoogle.fdBtnImg.setImageResource(R.drawable.ic_svg_arrow_r_18_18)
                }
            } else {
                // facebook
                if (it.second) {
                    viewBinding.aamFacebook.fdBtnText2.text =""
                    viewBinding.aamFacebook.fdBtnImg.setImageResource(R.drawable.ic_svg_arrow_r_18_18)
                }
            }
        }

        viewModel.bindThirdLoginResLiveData.observe(this) {
            // 绑定三方账号
            when (it.second) {
                AccountManagementVM.BindThirdState.SUCCESS -> {
                    if (it.first == LoginChannel.google) {
                        viewBinding.aamGoogle.fdBtnText2.text =
                            UserDataCenter.getAccountInfo()
                                ?.getThirdLoginInfo(LoginChannel.google)?.userName
                                ?: getString(R.string.connected)
                        viewBinding.aamGoogle.fdBtnImg.setImageResource(com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_checked)
                    } else {
                        viewBinding.aamFacebook.fdBtnText2.text =
                            UserDataCenter.getAccountInfo()
                                ?.getThirdLoginInfo(LoginChannel.facebook)?.userName
                                ?: getString(R.string.connected)
                        viewBinding.aamFacebook.fdBtnImg.setImageResource(com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_checked)
                    }
                }
                AccountManagementVM.BindThirdState.BOUND -> {
                    var channelName: String
                    if (it.first == LoginChannel.google) {
                        channelName = "Google account"
                    } else {
                        channelName = "Facebook account"
                    }
                    ConfirmDialog.Builder(this)
                        .setMessage("This $channelName was already connected to another Guang account.")
                        .hideCanCancelBtn()
                        .setSureButton(R.string.i_see) { dialog, _ ->
                            dialog.dismiss()
                        }
                        .create().show()
                }
                AccountManagementVM.BindThirdState.FAIL -> {
                    // 什么也不用做，VM中已弹toast
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_GOOGLE_LOGIN -> { //继续绑定三方登录账号
                if (resultCode == RESULT_OK) {
                    GoogleLoginUtils.handleGoogleSignInResult(
                        data,
                        onSuccess = {
                            if (it.email.isNullOrEmpty()) {
                                toast(CommUtils.getString(R.string.connect_fail2))
                            } else {
                                LoadingDialogManager.get().showLoading(this)
                                GoogleLoginUtils.fetchGoogleAccessToken(
                                    it.email!!
                                ) { accessToken ->
                                    if (accessToken.isNullOrEmpty()) {
                                        LoadingDialogManager.get().dismissLoading()
                                        toast(R.string.connect_fail2)
                                        return@fetchGoogleAccessToken
                                    }
                                    viewModel.bindThirdLogin(LoginChannel.google, accessToken)
                                }
                            }
                        },
                        onFail = {
                            toast(CommUtils.getString(R.string.connect_fail2))
                        }
                    )
                }
            }
        }
    }
}